package org.karelun.rabbit.bridge.ui.action;

import org.eclipse.emf.common.command.Command;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IWorkbenchPart;
import org.karelun.rabbit.bridge.ITransactionEditingDomain;
import org.karelun.rabbit.bridge.ITransactionEditingDomainProvider;

public class RabbitUndoAction extends Action{
	
	protected ITransactionEditingDomain domain;
	
	public RabbitUndoAction(ITransactionEditingDomain domain){
		super("Undo");
		this.domain=domain;
		update();
	}

	public RabbitUndoAction(){
		super("Undo");
	}
	
	public ITransactionEditingDomain getEdittingDomain() {
		return domain;
	}
	
	@Override
	public void run() {
		domain.getCommandStack().undo();
	}
	
	public void update() {
		setEnabled(canEnabled());
		Command undoCommand = domain.getCommandStack().getUndoCommand();
		if(undoCommand!=null&&undoCommand.getLabel()!=null){
			setText("Undo "+undoCommand.getLabel());
		}
		if(undoCommand!=null&&undoCommand.getDescription()!=null){
			setDescription("Undo "+undoCommand.getDescription());
		}
	}
	
	private boolean canEnabled() {
		boolean readOnly=domain.getCDOView().isReadOnly();
		boolean canUndo = domain.getCommandStack().canUndo();
		return !readOnly&&canUndo;
	}

	public void setActiveWorkbenchPart(IWorkbenchPart workbenchPart){
		if(workbenchPart instanceof ITransactionEditingDomainProvider){
			domain=((ITransactionEditingDomainProvider)workbenchPart).getTransactionEditingDomain();
		}
	}
}
